package com.mediacloud.app.newsmodule.view

import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlin.math.roundToInt
import com.mediacloud.app.newsmodule.R;

class BookView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : View(context, attrs, defStyleAttr) {
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?) : this(context, null)

    private val thickBitmap = BitmapFactory.decodeResource(resources, R.drawable.book_left)
    private val thickViewSrc: Rect = Rect(0, 0, thickBitmap.width, thickBitmap.height)
    private var thickViewDst: RectF = RectF()

    private var posterViewSrc: Rect = Rect()

    private var posterViewDst: RectF = RectF()
    private var mBitmap: Bitmap? = null
    private var zoomBitmap: Bitmap? = null
    private var paint = Paint()
    private var defaultWidth = 110.dp2pxInt()
    private var defaultHeight = 120.dp2pxInt()


    //控件的宽高比
    var ratio = 110 / 120f

    //书籍封面图的宽高比
    var posterRatio = 73 / 120f

    //封面图横向占比
    var posterPercent = 73 / 110f

    //书籍厚度和阴影的宽高比
    var thickRatio = 37 / 120f


    //
    init {
        paint.isAntiAlias = true
        paint.isDither = true
        paint.isFilterBitmap = true
    }


    override fun draw(canvas: Canvas?) {
        super.draw(canvas)
        mBitmap?.let {
            canvas?.drawBitmap(thickBitmap, thickViewSrc, thickViewDst, paint)
            posterViewSrc.left = 0
            posterViewSrc.right = it.width
            posterViewSrc.top = 0
            posterViewSrc.bottom = it.height

            posterViewDst.left = thickViewDst.right
            posterViewDst.right = posterViewDst.left + it.width * 1f
            posterViewDst.top = thickViewDst.top + 2.dp2px()
            posterViewDst.bottom = thickViewDst.bottom - 2.dp2px()
            canvas?.drawBitmap(it, posterViewSrc, posterViewDst, paint)
        }

    }

    fun loadBook(logo: Any?) {

        Glide.with(this).asBitmap().load(logo).listener(object : RequestListener<Bitmap> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                return true
            }

            override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {


                //view的宽高比小于了 正常情况下需要的宽高比 说明宽需要铺满 以宽为基准
                var postWidth = 0f
                var posHeight = 0f
                if (width * 1f / height < ratio) {
                    postWidth = width * posterPercent
                    posHeight = postWidth / posterRatio
                    val thickDstWidth = width * (1 - posterPercent)
                    val thickDstHeight = thickDstWidth / thickRatio
                    val offsetY = (height - thickDstHeight) / 2
                    thickViewDst.left = 0f
                    thickViewDst.top = offsetY
                    thickViewDst.right = thickDstWidth
                    thickViewDst.bottom = height - offsetY
                } else {
                    //以高铺满为基准
                    posHeight = height * 1f
                    postWidth = posHeight * posterRatio
                    val thickDstWidth = height * thickRatio
                    val offsetX = (width - thickDstWidth - postWidth) / 2
                    thickViewDst.left = offsetX
                    thickViewDst.top = 0f
                    thickViewDst.right = offsetX + thickDstWidth
                    thickViewDst.bottom = height * 1f
                }
                if (postWidth == 0f) {
                    return true
                }
                 zoomBitmap = createBitmap(resource, postWidth, posHeight)
                zoomBitmap?.let{zoomBitmap->
                    val src = floatArrayOf(
                        0f, 0f,
                        zoomBitmap.width.toFloat(), 0f,
                        zoomBitmap.width.toFloat(), zoomBitmap.height.toFloat(),
                        0f, zoomBitmap.height.toFloat()
                    )
                    val dst = floatArrayOf(
                        0f, 0f,
                        zoomBitmap.width.toFloat(), 10.dp2px(),
                        zoomBitmap.width.toFloat(), zoomBitmap.height - 10.dp2px(),
                        0f, height.toFloat()
                    )
                    val matrix = Matrix()
                    matrix.setPolyToPoly(src, 0, dst, 0, src.size shr 1);
                    mBitmap = Bitmap.createBitmap(zoomBitmap, 0, 0, zoomBitmap.width, zoomBitmap.height, matrix, true)
                    postInvalidate()
                }

                return true
            }
        }).submit()
    }

    fun release() {
//        zoomBitmap?.recycle()
//        mBitmap?.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val wMode = MeasureSpec.getMode(widthMeasureSpec)
        val hMode = MeasureSpec.getMode(heightMeasureSpec)
        if (wMode == MeasureSpec.AT_MOST && hMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(defaultWidth, defaultHeight)
        } else if (wMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(defaultWidth, MeasureSpec.getSize(heightMeasureSpec))
        } else if (hMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), defaultHeight)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }

    fun Number.dp2px(): Float {
        val f = toFloat()
        val scale: Float = Resources.getSystem().displayMetrics.density
        return f * scale + 0.5f
    }

    fun createBitmap(bm: Bitmap?, newWidth: Float, newHeight: Float): Bitmap {
        bm?.let {
            try {
                // 获得图片的宽高
                val width = bm.width
                val height = bm.height
                // 计算缩放比例
                val scaleWidth = newWidth / width
                val scaleHeight = newHeight / height
                // 取得想要缩放的matrix参数
                val matrix = Matrix()
                matrix.postScale(scaleWidth, scaleHeight)
                // 得到新的图片
                return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        val blank = Bitmap.createBitmap(newWidth.toInt(), newHeight.toInt(), Bitmap.Config.ARGB_8888)
        val canvas = Canvas(blank)
        canvas.drawColor(Color.parseColor("#887152"))
        return blank

    }

}


fun Number.dp2pxInt(): Int {
    val f = toFloat()
    val scale: Float = Resources.getSystem().displayMetrics.density
    return (f * scale + 0.5f).roundToInt()
}